<?php


namespace Littlexiaoshuishui\Upay\Gateways\Qfpay;

class Rsa
{
    private $public_key;
    private $private_key;
    public function __construct($public_key_path = '', $private_key_path = '')
    {
        $this->public_key = file_get_contents($public_key_path);
        $this->private_key = file_get_contents($private_key_path);
    }

    /**
     * RSA
     * @param $data
     * return
     */
    public function rsaSign($data) {
        $private_key = $this->private_key;
        $search = [
            "-----BEGIN RSA PRIVATE KEY-----",
            "-----END RSA PRIVATE KEY-----",
            "\n",
            "\r",
            "\r\n"
        ];

        $private_key=str_replace($search,"",$private_key);
        $private_key=$search[0] . PHP_EOL . wordwrap($private_key, 64, "\n", true) . PHP_EOL . $search[1];

        $res=openssl_get_privatekey($private_key);

        if($res)
        {
            openssl_sign($data, $sign,$res);
            openssl_free_key($res);
        }else {
            exit("private key error");
        }
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * RSA
     * @param $data
     * @param $sign
     * return
     */
    public function rsaCheck($data, $sign)  {
        $public_key = $this->public_key;
        $search = [
            "-----BEGIN PUBLIC KEY-----",
            "-----END PUBLIC KEY-----",
            "\n",
            "\r",
            "\r\n"
        ];
        $public_key=str_replace($search,"",$public_key);
        $public_key=$search[0] . PHP_EOL . wordwrap($public_key, 64, "\n", true) . PHP_EOL . $search[1];
        $res=openssl_get_publickey($public_key);
        $result = false;
        if($res){
            $result = (bool)openssl_verify($data, base64_decode($sign), $res);
            openssl_free_key($res);
        }else{
            error_log("public key error!");
        }
        return $result;
    }

}